import '../styles/index.scss';
import slugify from '@sindresorhus/slugify';
import ClipboardJS from 'clipboard';

const __processors = [
    {
        key: 'slug',
        action: (trigger) => {
            const selector = trigger.getAttribute('data-clipboard-target');
            const input = document.querySelector(selector);
            const slug = slugify(input.value);
            input.value = '';
            return slug;
        },
    },
];

export const slug = () => {
    // 初始化剪贴板
    const clipboard = new ClipboardJS('[data-clipboard-target]', {
        text: function (trigger) {
            const processor = __processors.find((x) => x.key === trigger.getAttribute('data-process'));
            return processor.action(trigger);
        },
    });

    clipboard.on('success', function (e) {
        const tooltip = bootstrap.Tooltip.getInstance(e.trigger);
        if (!tooltip) {
            console.log('已复制');
            return;
        }

        tooltip.setContent({ '.tooltip-inner': '已复制' });
        tooltip.show();

        // 隐藏之后重置颜色值
        e.trigger.addEventListener('hidden.bs.tooltip', () => {
            tooltip.setContent({ '.tooltip-inner': e.trigger.getAttribute('data-bs-title') });
        });
    });
};
